<?php

class UnderwoodPagesFactory extends AbstractTWLPagesFactory {

    /**
     * @return UnderwoodPagesFactory
     */
    public static function getInstance() { return parent::doGetInstance(get_class()); }

    /**
     * @return AbstractTWLSitePage
     */
    protected function createPageByPath($path) {

        if ($hPage = UnderwoodMenu::getInstance()->getPageConfigByPath($path)) {

            if (!empty($hPage['auth']) && !$this->isCorrectUser($hPage['auth'])) {
                return new ForbidenUnderwoodSitePage();
            }

            return new NormalUnderwoodSitePage($hPage['title'], $hPage['controller'], $hPage);

        } else {
            return new NotFoundUnderwoodSitePage();
        }
    }

    private function isCorrectUser($data) {

        if (!isset($_SERVER['PHP_AUTH_USER'])) {

            header('WWW-Authenticate: Basic realm="My Realm"');
            header('HTTP/1.0 401 Unauthorized');

            return false;
        }

        list($correctUserHash, $correctPassHash) = explode(':', $data);

        return (sha1($_SERVER['PHP_AUTH_USER']) == $correctUserHash) &&
               (sha1($_SERVER['PHP_AUTH_PW']) == $correctPassHash);
    }
}

?>